//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import s from "./UserAppList.module.less";
import { List } from "antd";
import { request } from "@/utils/request";
import type { AppInfo } from "@/api/appstore";
import { list_app_by_id } from "@/api/appstore";
import { list_app as list_user_app } from "@/api/user_app";
import { useStores } from "@/hooks";
import UserAppItem from "./components/UserAppItem";
import { get_global_server_addr } from "@/api/client_cfg";
import type { UserServerInfo } from '@/api/user_server';
import { list_server } from '@/api/user_server';

export interface UserAppListProps {
    onCount: (count: number) => void;
}

const UserAppList = (props: UserAppListProps) => {
    const userStore = useStores('userStore');

    const [userAppList, setUserAppList] = useState<AppInfo[]>();
    const [userServerList, setUserServerList] = useState<UserServerInfo[] | null>(null);

    const loadUserAppList = async () => {
        if (userStore.sessionId == "") {
            setUserAppList([]);
            props.onCount(0);
            return;
        }
        const appListRes = await request(list_user_app({
            session_id: userStore.sessionId,
        }));
        const addr = await get_global_server_addr();

        const res = await request(list_app_by_id(addr, {
            app_id_list: appListRes.app_id_list,
            session_id: userStore.sessionId,
        }));
        setUserAppList(res.app_info_list);
        props.onCount(res.app_info_list.length);
    };

    const loadUserServerList = async () => {
        if (userStore.sessionId == "") {
            setUserServerList(null);
        } else {
            const res = await list_server();
            setUserServerList(res);
        }
    };

    useEffect(() => {
        loadUserAppList();
        loadUserServerList();
    }, [userStore.sessionId]);

    return (
        <div className={s.panel_wrap}>
            <List
                grid={{
                    gutter: 16,
                }}
                dataSource={userAppList}
                renderItem={(item, itemIndex) => (
                    <List.Item key={item.app_id}>
                        <UserAppItem appInfo={item} firstApp={itemIndex == 0}
                            userServerList={userServerList} onRemove={() => loadUserAppList()} onSetTop={() => loadUserAppList()}
                            onChangeUserServer={() => loadUserServerList()} />
                    </List.Item>
                )}
            />
        </div>
    );
}

export default observer(UserAppList);